#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int isPrime(int n)
{
	if (n==2 || n==3 || n==5 || n== 7)return 1;
	if (n%2 == 0|| n%3 == 0 || n==1)return 0;
	int i;
	for (i=5; i<=floor(sqrt(n)); i+=6) {
		if (n%i == 0 || n%(i+2) == 0)return 0;
	}
	return 1;
}

int isPandigital(int n)
{
	int x=0, org = n, i;
	while (n) {
		n /=10;
		x++;
	}
	n = org;
	int *digits = (int *)malloc(sizeof(int)*(x+1));
	for (i=1; i<=x; i++)digits[i]=0;

	while (n) {
		if (n%10 > x)return 0;
		digits[n%10]++;
		if (digits[n%10] > 1) return 0;
		n /=10;
	}
	for (i=1; i<=x; i++)
		if (digits[i] != 1)return 0;
	free(digits);
	digits = NULL;
	return 1;
}

int reverse(int n)
{
	int r=0;
	while (n) {
		r = r*10+n%10;
		n /=10;
	}
	return r;
}
int main()
{
	printf("%d\n", isPandigital(987654103));
	int digits=4, n, i, max=0, r;
	for (digits=7; digits<8;digits++) {
		i = digits;
		n = i;
		while (i>1) { n = n*10 + (i-1); i--;}		
		r = reverse(n);
		//printf("%d\n", r);
		while (n>=r) {
			if (isPandigital(n) && n > max && isPrime(n)) {
				max = n;
				break;
			}
			n -=2;
		}
	}
	printf("%d\n", max);
}
